﻿if (typeof Axis.Admin == "undefined") Axis.Admin = {};
if (typeof Axis.Admin.QuestionPath == "undefined") Axis.Admin.QuestionPath = {};
Axis.Admin.QuestionPath.Entry = {
    currentProject: -1,
    currentAnswer: -1,
    OldPath: [],
    listQuestion: [],
    listAnswer: [],
    listConditionMethod: [],
    LoadAnswserByQuestion: function (obj) {
        var thisObj = this;
        var QuesID = $(obj).val();
        var listAnswer = [];
        $.each(thisObj.listAnswer, function (index, item) {
            if (item.QuesID == QuesID) {
                listAnswer = item.ListAnswer;
                return false;
            }
        });
        var logicRule = $(obj).parent().parent();
        var objOperator = $(logicRule).find('.unit-operator-container');
        var objAnswer = $(logicRule).find('.atom-2-container');
        var htmlOption = "";
        var htmlPattern = ' <div class="option">'
                                    + '<input type="checkbox" class="input input-checkbox" id="atom-{0}-{1}" value="{2}" />'
                                    + '<label for="atom-{0}-{1}">{3}</label>'
                                    + '</div>';
        $.each(listAnswer, function (index, item) {
            htmlOption += $.string.Format(htmlPattern, QuesID, item.ID, item.Value, item.Caption);
        });
        $(objAnswer).remove();
        htmlOption = '<div class="logic-atom atom-2-container">' + htmlOption + '</div>'
        $(htmlOption).insertAfter(objOperator);
    },
    InitLogicRule: function () {
        var thisObj = this;
        $("#LogicGroup").append(thisObj.CreateLogicRule());
        $("#LogicNextQuestion").html(thisObj.CreateHtmlListQuestion(1));
        $("#LogicCurrentQuestion").html(thisObj.CreateHtmlListQuestion());

    },
    CreateLogicRule: function () {
        var thisObj = this;
        var pattern = '<li class="logic-rule">'
                      + '<div class="logic-atom-prefix">If:</div>'
                      + '<div class="logic-atom atom-1-container">{0}</div>'
                      + '<div class="logic-atom unit-operator-container">{1}</div>';

        return $.string.Format(pattern, thisObj.CreateHtmlListQuestion(), thisObj.CreateHtmlListOperator());
    },
    CreateHtmlListOperator: function () {
        var thisObj = this;
        var patternSelect = '<select class="input input-select logic-select unit-operator"  data-field="">{0}</select>';
        var patternlOption = "<option class='question-type-radio' value='{0}'>{1}</option>";
        var htmlOption = "";
        $.each(thisObj.listConditionMethod, function (index, item) {
            htmlOption += $.string.Format(patternlOption, item.Value, item.Name);
        });
        return $.string.Format(patternSelect, htmlOption);
    },
    CreateHtmlListQuestion: function (isNext) {
        var thisObj = this;
        var listOption = "";
        var patternSelect = '<select class="input input-select logic-select atom-1 " style="width:100%;" data-field="522a9fcbe45ea" {1} >{0}</select>';
        var patternlOption = "<option class='question-type-radio' value='{0}'>{1}</option>";
        var htmlOption = "<option value='-1'>...</option>";
        var action = ' onchange="LoadAnswserByQuestion(this)" ';
        if (isNext != undefined) {
            htmlOption = "<option value='-100'>Dừng lại</option>";
            action = '';
        }
        $.each(thisObj.listQuestion, function (index, item) {
            htmlOption += $.string.Format(patternlOption, item.ID, item.QuestionText);
        });
        return $.string.Format(patternSelect, htmlOption, action);
    },
    Update: function (type, opts) {
        var thisObj = this;
        var data = thisObj.GetInputData(type, $("#txtID").val());
        console.log('Update', data);
        if (type != "INSERT")
            data = data.replace(' ID="0"', $.string.Format(' ID="{0}"', opts.ID));
        var pData = JSON.stringify({ InputValue: data }); //'{' + $.string.Format('"InputValue":{0}', data) + '}';
        var pCallback = function (objData) {
            var data = eval("(" + objData.d + ")");
            if (data.IsSuccessfull) {
                $.CAlert.Success({ Title: "Thành công",
                    Content: data.Description
                }, function () {
                    Axis.Admin.QuestionPath.List.Grid.Reload();
                });
            }
            else
                $.CAlert.Error({ Title: "Lỗi",
                    Content: data.Description
                });
        };
        thisObj.LoadData('Service/ManagerQuestionService.asmx/ActionQuestionnaireConditions', pData, pCallback);
    },
    DeleteQuestion: function (obj) {
        var thisObj = this;
        var Ques = $(obj).attr('question');
        var Question = $(obj).parent();
        var Answer = $(Question).next();
        $(Question).remove();
        $(Answer).remove();
        var pos = -1;
        $.each(thisObj.CurrentPath, function (index, item) {
            if (item.ID == Ques)
                pos = index;
        });
        if (pos > -1)
            thisObj.CurrentPath.splice(pos, 1);
        thisObj.CreateListNextQuestion();
    },
    LoadListQuestion: function () {
        var thisObj = this;
        var projectID = $("#ctl00_AdministratorBody_ddlProjectList").val();
        if (projectID == '')
            return;
        //cung project nen khong load lai danh sach cau hoi
        if (thisObj.currentProject == projectID) {
            thisObj.InitLogicRule();
            return;
        }
        thisObj.currentProject = projectID;
        thisObj.listQuestion = null;
        thisObj.listAnswer = null;
        thisObj.currentAnswer = 0;
        var pData = '{' + $.string.Format('"ProjectID":{0}', projectID) + '}';
        var pCallback = function (objData) {
            thisObj.listQuestion = eval("(" + objData.d + ")");
            thisObj.listAnswer = new Array();
            thisObj.LoadListAnswer();
        };
        thisObj.LoadData('Service/ManagerQuestionService.asmx/GetQuestionList', pData, pCallback);
    },
    LoadListAnswer: function () {
        var thisObj = this;
        thisObj.listQuestion != null;
        if (thisObj.listQuestion.length > 0)
            if (thisObj.currentAnswer < thisObj.listQuestion.length) {
                var Ques = thisObj.listQuestion[thisObj.currentAnswer++];
                var pData = '{' + $.string.Format('"Context":"{0}",QuestionID:{1}', "PATH", Ques.ID) + '}';
                var pCallback = function (objData) {
                    thisObj.listAnswer.push({ QuesID: Ques.ID, ListAnswer: eval("(" + objData.d + ")") });
                    thisObj.LoadListAnswer();
                };
                thisObj.LoadData('Service/ResponseOptionService.asmx/GetQuestionareListByContext', pData, pCallback);
            }
            else {
                thisObj.InitLogicRule();
            }
    },
    Reset: function () {
        var thisObj = Axis.Admin.QuestionPath.Entry;
        $("#txtID").val(0);
        $("#LogicGroup").html('');
        $("#LogicNextQuestion select").html('');
        $("#txtDescription").val('');
        $("#txtNameCondition").val('');
        thisObj.LoadListQuestion();
        //
    },
    GetInputData: function (Action, ConditionID) {

        var pattenInputValue = '<InputValue Action="{0}" ProjectID="{1}"  ID="{2}" QuestionnaireID="{3}" Code="" Name="{6}" Descriptions="{7}" NextQuestionnaireMethod="{4}" NextQuestionnaireID="{5}" />'; //[KeyExtend]
        var pattenDetailValue = '<Detail QuestionnaireID="{0}" GroupZOrder="{1}" GroupMethod="{2}" Method="{3}" ResponseValue="{4}"/>';
        var projectID = $("#ctl00_AdministratorBody_ddlProjectList").val();
        if (Action == 'DELETE')
            return $.string.Format('<InputValue ID="0" Action="{0}" ProjectID="{1}" [KeyExtend]/>', Action, projectID);
        var NextQuestionnaireID = $("#LogicNextQuestion select").val();
        var CurrentQuestionnaireID = $("#LogicCurrentQuestion select").val();
        var NextQuestionnaireMethod = $("#NextQuestionnaireMethod select").val();
        var listCondition = new Array();
        var listBridge = new Array();
        var Result = "";
        $.each($("#LogicGroup .logic-rule"), function (index, item) {
            var Question = $(item).find('select.atom-1');
            var Operator = $(item).find('select.unit-operator');
            var Response = $(item).find("[type='checkbox']:checked");
            var arrayChecked = new Array();
            $.each(Response, function (i, Res) {
                arrayChecked.push($(Res).val());
            });
            listCondition.push({ QuesID: $(Question).val(), Method: $(Operator).val(), ResponseValue: arrayChecked.toString() });
        });

        $.each($("#LogicGroup .logic-bridge"), function (index, item) {
            var bridge = $(item).find('select');
            listBridge.push($(bridge).val());
        });

        if (CurrentQuestionnaireID) {
            Result = $.string.Format(pattenInputValue, Action, projectID, ConditionID, CurrentQuestionnaireID, NextQuestionnaireMethod, NextQuestionnaireID, $("#txtNameCondition").val(), $("#txtDescription").val());
        }
        if (listCondition.length > 0) {
            var first = listCondition[0];
            Result += $.string.Format(pattenDetailValue, first.QuesID, 0, 0, first.Method, first.ResponseValue);
        }

        for (var i = 1; i < listCondition.length; i++) {
            var item = listCondition[i];
            var bridge = listBridge[i - 1];
            Result += $.string.Format(pattenDetailValue, item.QuesID, i, bridge, item.Method, item.ResponseValue);
        }

        return Result;
    },
    LoadData: function (pUrl, pData, pCallback) {
        $.ajax({
            url: pUrl,
            type: 'POST',
            data: pData,
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function (jqXHR, settings) {
            },
            success: function (pData, textStatus, jqXHR) {
                if (pCallback != undefined)
                    pCallback(pData);
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    AddLogicRule: function (selected) {
        var thisObj = this;
        var option = '<option value="1" selected="selected">and</option>'
		            + '<option value="0">or</option>';
        if (selected != undefined)
            if (selected == "0")
                option = '<option value="1">and</option>'
		            + '<option value="0" selected="selected">or</option>';

        var htmlLinkQuestion = '<li class="logic-bridge">'
	                            + '<select class="input input-select">'
		                        + option
	                            + '</select>'
                                + '</li>';
        $("#LogicGroup").append(htmlLinkQuestion);
        $("#LogicGroup").append(thisObj.CreateLogicRule());
        var delQuestion = '<a title="Remove This Rule" class="icon-kill logic-rule-remove"><img src="Css/img/cancel.png" class="logic-rule-delete"/></a> </li>';
        var lastAnswer = $('#LogicGroup .logic-rule').last();
        $(lastAnswer).append(delQuestion);
    },
    RemoveLogicRule: function (obj) {
        var logicRule = $(obj).parent().parent();
        var logicBridge = $(logicRule).prev();

        $.CAlert.Confirm({
            Title: "Xóa logic",
            Content: $.string.Format("Bạn muốn xóa logic với cấu đang được chọn")
        }, function (isOK) {
            if (isOK) {
                $(logicRule).remove();
                $(logicBridge).remove();
            }
        });
    },
    LoadConditionDetail: function () {
        var thisObj = this;
        var projectID = $("#ctl00_AdministratorBody_ddlProjectList").val();
        var QuesID = $("#txtID").val();
        var pData = JSON.stringify({ QuestionID: QuesID, ProjectID: projectID });
        var pCallback = function (data) {
            var objData = eval("(" + data.d + ")");
            thisObj.SetConditionDetailValue(objData);
        };
        thisObj.LoadData('Service/ResponseOptionService.asmx/GetQuestionnaireConditionsDetails', pData, pCallback);
    },
    SetConditionDetailValue: function (objData) {
        var thisObj = this;
        if (objData.length > 0) {
            var item = objData[0];
            thisObj.SetConditionDetailValueByQuestionID(0, item);
        }
        for (var i = 1; i < objData.length; i++) {
            var item = objData[i];
            thisObj.AddLogicRule(item.GroupMethod);
            thisObj.SetConditionDetailValueByQuestionID(i, item);
        }
    },
    SetConditionDetailValueByQuestionID: function (index, item) {
        var ResponseValue = item.ResponseValue.split(',');
        var note = $.string.Format("#LogicGroup li.logic-rule:eq({0})", index);
        $(note + " .atom-1-container select").val(item.QuestionnaireID);
        $(note + " .unit-operator-container select").val(item.Method);
        $(note + " .atom-1-container select").trigger('change');
        window.setTimeout(function () {
            $.each($(note + " .atom-2-container input[type='checkbox']"), function (index, Res) {
                var check = false;
                for (var i = 0; i < ResponseValue.length; i++) {
                    if (ResponseValue[i] == $(Res).val()) {
                        check = true;
                        break;
                    }
                }
                if (check == true)
                    $(Res).attr('checked', 'checked');
            });
        }, 100);

    },

    LoadCondition: function (objData) {
        var thisObj = this;
        console.log('LoadCondition', objData);
        $("#LogicCurrentQuestion select").val(objData.QuestionID);
        $("#txtNameCondition").val(objData.Name);
        $("#txtDescription").val(objData.Description);
        $("#LogicNextQuestion select").val(objData.NextQuestionID);
        $("#NextQuestionnaireMethod select").val(objData.NextQuestionnaireMethod);
    },
    LoadConditionMethod: function () {
        var thisObj = this;
        var pData = '{"Method":"QuestionnaireConditionMethod"}';
        var pCallback = function (data) {
            var objData = eval("(" + data.d + ")");
            thisObj.listConditionMethod = objData;
        };
        thisObj.LoadData('Service/ResponseOptionService.asmx/GetConditionMethod', pData, pCallback);
    },
    LoadNextQuestionnaireMethod: function () {
        var thisObj = this;
        var pData = '{"Method":"NextQuestionnaireMethod"}';
        var pCallback = function (data) {
            var objData = eval("(" + data.d + ")");
            var patternSelect = '<select class="input input-select logic-select unit-operator"  data-field="">{0}</select>';
            var patternlOption = "<option class='question-type-radio' value='{0}'>{1}</option>";
            var htmlOption = "";
            $.each(objData, function (index, item) {
                htmlOption += $.string.Format(patternlOption, item.Value, item.Name);
            });
            $("#NextQuestionnaireMethod").html($.string.Format(patternSelect, htmlOption));

        };
        thisObj.LoadData('Service/ResponseOptionService.asmx/GetConditionMethod', pData, pCallback);
    }
};

function LoadAnswserByQuestion(obj) {
    var thisObj = Axis.Admin.QuestionPath.Entry;
    thisObj.LoadAnswserByQuestion(obj);
}
$(function () {
    var thisObj = Axis.Admin.QuestionPath.Entry;
    $(".logic-rule-add").live('click', function () {
        thisObj.AddLogicRule();
    });
    $(".logic-rule-delete").live('click', function () {
        thisObj.RemoveLogicRule(this);
    });
    thisObj.LoadConditionMethod();
    thisObj.LoadNextQuestionnaireMethod();
});

function GetInputData(Action, ConditionID) {
    var thisObj = Axis.Admin.QuestionPath.Entry;
    thisObj.GetInputData(Action, ConditionID);
}